package com.bgdCA.controller;

import com.bgdCA.auth.entity.TokenInfo;
import com.bgdCA.domain.User;
import com.bgdCA.auth.exception.BiccException;
import com.bgdCA.auth.properties.JwtProperties;
import com.bgdCA.service.LoginService;
import com.bgdCA.auth.utils.CookieUtils;
import com.bgdCA.auth.utils.JwtUtils;
import com.bgdCA.response.CodeMsg;
import com.bgdCA.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/8/1 11:44
 * @Version 1.0
 **/
@Slf4j
@Controller
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    private JwtProperties prop;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String, String> map,
                        HttpServletRequest request,
                        HttpServletResponse response) {

        String username = map.get("username");
        String password = map.get("password");
        String token = "";

        //查找用户
        User user = loginService.findUser(username);
        //判断用户是否为空
        if (user == null) {
            return Result.error(CodeMsg.LOGIN_USER_NOT_FOUND);
        }
        log.debug(user.toString());
        //判断密码是否正确
        if (!password.equals(user.getPassword())) {
            return Result.error(CodeMsg.PASSWORD_NOT_RIGHT);
        }
        TokenInfo tokenInfo = new TokenInfo(user.getId(), user.getUsername(), user.getAuthorization());
        try {
            //生成token
            token = JwtUtils.generateToken(
                    tokenInfo,
                    prop.getPrivateKey(), prop.getExpire());
            log.info("token生成:" + token);
        } catch (Exception e) {
            return Result.error(CodeMsg.GENERATE_TOKEN_FAILURE);
        }
        //排除token为空情况
        if (token.isEmpty()) {
            return Result.error(CodeMsg.GENERATE_TOKEN_IS_EMPTY);
        }
        try {
            //注意cookies中httpOnly以代码形式打开，需要关闭请手动关闭
            //存入cookies
            CookieUtils.setCookie(
                    request, response,
                    prop.getCookiesName(),
                    token,
                    prop.getCookiesMaxAge(), true);

        } catch (BiccException e) {
            e.printStackTrace();
        }
        return Result.success(user);
    }


}
